package com.tangqi.mail;

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

//import javax.mail.internet.NewsAddress;

/**
 *  ------------------------流程------------------------
 *  1,获取系统Properties.
 *	Properties props = System.getProperties();
 *	2,将您的SMTP服务器名添加到mail.smtp.host关键字的属性中.
 *	Props.pout("mail.smtp.host" ,host);
 *	3,获取基于Properties Session对象.
 *	Session session = Session.getDefaultInstance(props,null);
 *	4,从Session创建一个MimeMessage.
 *	MimeMessage message = new MimeMessage(session);
 *	5,设置消息from域.
 *	Message.setForm(new InternetAddress(from));
 *	6,设置to域.
 *	Message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
 *	7,设置消息主题.
 *	message.setSubject( "HelloJavaMail" );
 *	8,设置消息内容.
 *	Message.setText("Welcome to JavaMail");
 *	9,发送消息.
 *	Transport.send(message);
 *	10,在编译用运的时候传递MSTP服务器,from地址,to地址.
 *  ---------------------------------------------------
 *  @author qtang
 *
 */

public class SendMail {

	private String mailFrom = null;
	
	private String mailTo = null;
	private String mailbccTo = null;
	private String mailccTo = null;

	private String subject;
	private String messageContentMimeType = null;
	private String msgContent;
	private Vector attachedFileList;
	
	private String smtpHost = null;
	private boolean debug = false;
	private String messageBasePath = null;
	
	private StringBuffer warningMessage = new StringBuffer();
	
	private Authenticator auth = null;
	private String mailAccount = null;
	private String mailPass = null;
	private Session session = null;
	
	Properties agproperties = new Properties();

	public void init() {		
		java.io.InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.properties");
        try {
			agproperties.load(in);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	/**
	 * 
	 */
	public void loadMailInfo(){
		mailFrom = agproperties.getProperty("mailFrom");
		mailTo = agproperties.getProperty("mailTo");
		mailccTo = agproperties.getProperty("mailccTo");
		mailbccTo = agproperties.getProperty("mailbccTo");
		
		subject = agproperties.getProperty("subject");
		msgContent = agproperties.getProperty("msgContent");
		messageContentMimeType = agproperties.getProperty("messageContentMimeType");
		
		messageBasePath = System.getProperty("user.dir");
		
		attachedFileList = new Vector<String>();
		attachedFileList.add("testAtt1.zip");
		attachedFileList.add("testAtt2.zip");
		
		smtpHost = agproperties.getProperty("smtpHost");
		
		mailAccount = agproperties.getProperty("mailAccount");
		mailPass = agproperties.getProperty("mailPass");
		
		auth = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(mailAccount,mailPass);
			}
		};
		
		Properties props = System.getProperties();
		props.put("mail.smtp.host", smtpHost);
		props.put("mail.smtp.auth", "true");
		session = Session.getInstance(props, auth);
	}
	
	public SendMail() {
		super();
		init();
		loadMailInfo();
	}
	
	public Session getSession() {
		return session;
	}

	/**
	 * 
	 * @param session
	 * @param msg
	 * @throws IOException
	 * @throws MessagingException
	 */
	private void fillMail(Session session, MimeMessage msg) throws IOException,MessagingException {

		String fileName = null;
		//set mail from 
		if (mailFrom != null) {
			msg.setFrom(new InternetAddress(mailFrom));
			System.out.println("Mail from：" + mailFrom);
		} else {
			warningMessage.append("mail from can not be empty!");
		}
		//set mail to 
		if (mailTo != null) {
			InternetAddress[] address = InternetAddress.parse(mailTo);
			msg.setRecipients(Message.RecipientType.TO, address);
			System.out.println("Mail To：" + mailTo);
		} else {
			warningMessage.append("mail from can not be empty!");
		}
		//set mail cc 
		if (mailccTo != null) {
			InternetAddress[] ccaddress = InternetAddress.parse(mailccTo);
			System.out.println("Mail CC ：" + mailccTo);
			msg.setRecipients(Message.RecipientType.CC, ccaddress);
		}
		//set mail bcc 
		if (mailbccTo != null) {
			InternetAddress[] bccaddress = InternetAddress.parse(mailbccTo);
			System.out.println("Mail BCC：" + mailbccTo);
			msg.setRecipients(Message.RecipientType.BCC, bccaddress);
		}
		//set mail subject 
		if(subject!=null){
			msg.setSubject(subject);
		}
		//set reply to
		InternetAddress[] replyAddress = { new InternetAddress(mailFrom) };
		msg.setReplyTo(replyAddress);
		
		// create and fill the first message part
		Multipart mPart = new MimeMultipart();
		MimeBodyPart mBodyContent = new MimeBodyPart();
		if (msgContent != null){
			mBodyContent.setContent(msgContent, messageContentMimeType);
		}else{
			mBodyContent.setContent("", messageContentMimeType);
		}
		mPart.addBodyPart(mBodyContent);
		
		// attach the file to the message
		if (attachedFileList != null) {
			for (Enumeration fileList = attachedFileList.elements(); fileList.hasMoreElements();) {
				fileName = (String) fileList.nextElement();
				MimeBodyPart mBodyPart = new MimeBodyPart();

				// attach the file to the message
				FileDataSource fds = new FileDataSource(messageBasePath+"\\"+ fileName);
				System.out.println("Mail Attached name：" + messageBasePath +"\\"+ fileName);
				mBodyPart.setDataHandler(new DataHandler(fds));
				mBodyPart.setFileName(fileName);
				mPart.addBodyPart(mBodyPart);
			}
		}
		msg.setContent(mPart);
		msg.setSentDate(new Date());
	}

	

	/**
	 * 发送e_mail，返回类型为int 当返回值为1时，说明邮件发送成功 当返回值为0时，说明邮件发送失败
	 */
	public int sendMail(Session session) throws IOException, MessagingException {				
		session.setDebug(debug);
		MimeMessage msg = new MimeMessage(session);
		try {
			fillMail(session, msg);
			Transport.send(msg);
		} catch (MessagingException mex) {
			System.out.println("Fail to send mail：");
			mex.printStackTrace();
			return 0;
		} 
		System.out.println("Success to send mail!");
		return 1;
	}

	
	public static void main(String[] args) {
		SendMail sendMail = new SendMail();
		try {
			sendMail.sendMail(sendMail.getSession());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
}
